package com.quatrix.openphantasy.client.ui;

import com.google.gwt.core.client.GWT;
import com.quatrix.openphantasy.client.datasource.CountryDS;
import com.quatrix.openphantasy.client.datasource.LeagueDS;
import com.quatrix.openphantasy.client.datasource.TeamDS;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;


public class SeasonSetupWindow extends Window {
	private final DynamicForm _form;
	
	SeasonSetupWindow() {
		_form = new DynamicForm();
		
		final SelectItem countrySelect = new SelectItem();
		final SelectItem leagueSelect = new SelectItem() {
			protected Criteria getPickListFilterCriteria() {
				Criteria retval = new Criteria();
				retval.addCriteria("country", (String) countrySelect.getValue());
				return retval;
			}
		};
		final SelectItem teamSelect = new SelectItem() {
			protected Criteria getPickListFilterCriteria() {
				Criteria retval = new Criteria();
				try {
					retval.addCriteria("lastLeague", (Integer) leagueSelect.getValue());
				} catch (Exception e) {
					GWT.log("exception", e);
				}
				return retval;
			}			
		};
		
		
		countrySelect.setOptionDataSource(CountryDS.getInstance());
		countrySelect.setName("country");
		countrySelect.setDisplayField("name");
		countrySelect.setValueField("code");
		countrySelect.setTitle("Country");
		countrySelect.addChangedHandler(new ChangedHandler() {

			public void onChanged(ChangedEvent event) {
				_form.clearValue("league");
			}
			
		});
		
		leagueSelect.setOptionDataSource(LeagueDS.getInstance());
		leagueSelect.setName("league");
		leagueSelect.setDisplayField("name");
		leagueSelect.setValueField("id");
		leagueSelect.setTitle("League");
		leagueSelect.addChangedHandler(new ChangedHandler() {

			public void onChanged(ChangedEvent event) {
				_form.clearValue("teams");
			}
			
		});
		
		
		teamSelect.setOptionDataSource(TeamDS.getInstance());
		teamSelect.setName("teams");
		teamSelect.setDisplayField("name");
		teamSelect.setValueField("id");
		teamSelect.setMultiple(false);
		teamSelect.setTitle("Teams");
		
		_form.setFields(countrySelect, leagueSelect, teamSelect);
	}
	
	@Override
	protected void onInit() {
		setTitle("Season Setup");
		addItem(_form);
		setWidth(600);
		setHeight(300);
		setAutoCenter(true);
		setIsModal(true);
	}
	
	public static SeasonSetupWindow createWidget() {
		return new SeasonSetupWindow();
	}
}
